package com.itheima.factory;

import com.itheima.pojo.Address;
import com.itheima.pojo.User;

import java.io.InputStream;
import java.util.*;

/*
* 工厂类：负责生产Bean对象
* */
public class BeanFactory {
    //创建一个容器（数组，集合（list  map））用来存储创建的每一个bean对象
    private static Map<String,Object> map=new HashMap();


    static {
       try {
           InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
           Properties pro=new Properties();
           pro.load(is);
           Enumeration enums = pro.propertyNames();
           while (enums.hasMoreElements()){
               //获取bean.properties中每一个key
               String key = (String) enums.nextElement();
               //通过key获取value(com.itheima.pojo...)
               String className=pro.getProperty(key);
               Object obj = Class.forName(className).newInstance();
               //将创建的bean对象存入map容器
               map.put(key,obj);
           }


       }catch (Exception e){
           e.printStackTrace();
       }
    }


    public static Object getBean(String name)throws Exception{
        return map.get(name);
    }

   /* //通用1
    public static Object getBean(String name)throws Exception{
        //name --> user
        //读取配置文件的信息
        //ResourceBundle:读取properties配置文件工具类，
        // 要求：1、properties文件必须存放在源路径下
        //      2、读取时只需要文件名称，不要后缀
        ResourceBundle bundle = ResourceBundle.getBundle("bean");
        //User对象 name--->com.itheima.pojo.User
        Object obj = Class.forName(bundle.getString(name)).newInstance();
        return obj;
    }


    //通用1
    public static Object getObject1(String name)throws Exception{
        //反射
        Object obj = Class.forName(name).newInstance();
        return obj;
    }


    //通用
    public static Object getObject()throws Exception{
        //反射
        Object obj = Class.forName("com.itheima.pojo.Address").newInstance();
        return obj;
    }



    //创建User对象
    public static User getUser() throws Exception{
        //反射
        Object obj = Class.forName("com.itheima.pojo.User").newInstance();

        return new User();
    }

    //创建User对象
    public static Address getAddress(){
        return new Address();
    }*/
}
